package com.elinkway.infinitemovies.http.parser;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.ChannelNewParams;
import com.elinkway.infinitemovies.bean.MainHeaderBean;
import com.elinkway.infinitemovies.bean.MainHeaderList;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainHeaderListParser extends LVideoMobileParser<MainHeaderList> {

	private JSONArray arr;

	@Override
	public MainHeaderList parse(JSONObject data) throws Exception {

		MainHeaderList mainHeaderList = new MainHeaderList();
		if(arr != null && arr.length() > 0){
			ArrayList<MainHeaderBean> headerBeanList = new ArrayList<>();
			MainHeaderBean bean = null;
			JSONObject obj = null;
			for (int i = 0; i < arr.length(); i++) {
				obj = arr.getJSONObject(i);
				if(obj != null){
					bean = new MainHeaderBean();
					bean.setName(obj.optString("name"));
					bean.setPage(obj.optString("page"));
					bean.setVt(obj.optString("vt"));
					bean.setCornerIcon(obj.optString("corner_icon"));
					bean.setIcon(obj.optString("icon"));
					bean.setIsDefault(obj.optString("is_default"));
					bean.setSearchQuery(obj.optString("search_query"));
					JSONArray paramsArr = obj.optJSONArray("channel");
					if(paramsArr != null && paramsArr.length() > 0){
						List<ChannelNewParams> paramsList = new ArrayList<>();
						JSONObject channelObj = null;
						ChannelNewParams newParams = null;
						for (int j = 0; j < paramsArr.length(); j++){
							channelObj = paramsArr.optJSONObject(j);
							if(channelObj != null){
								newParams = new ChannelNewParams();
								newParams.setId(channelObj.optString("id"));
								newParams.setName(channelObj.optString("name"));
								newParams.setOrderby(channelObj.optString("orderby"));
								newParams.setArea(channelObj.optString("area"));
								newParams.setSubcategory(channelObj.optString("subcategory"));
								newParams.setYear(channelObj.optString("year"));
								paramsList.add(newParams);
							}
						}
						bean.setParamsList(paramsList);
					}
					headerBeanList.add(bean);
				}
			}
			mainHeaderList.setHeaderList(headerBeanList);
			SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.HOME_TAB_JSON, arr.toString());
		}
		return mainHeaderList;
	}

	@Override
	protected JSONObject getData(String data) throws JSONException {
		arr = new JSONArray(data);
		data = "{\"data\":\"data\"}";
		return super.getData(data);
	}

	public void setArr(JSONArray a){
		this.arr = a;
	}
}
